
from  langchain_core.tools import tool
from  langchain.tools.render import render_text_description
from langchain_core.output_parsers import JsonOutputParser,StrOutputParser
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from operator import itemgetter
from langchain_core.runnables import RunnablePassthrough,RunnableLambda,Runnable
from typing import  Union
from langchain_core.messages import AIMessage
from langchain.memory import ConversationBufferMemory
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain.chains.conversation.base import ConversationChain
from langchain.schema import messages_to_dict,messages_from_dict


import requests
import json
import time
import pickle



# 模型定义
ZHIPUAI_API_KEY = '794380a4cee054a0f96bb2844b41fd12.X4t70kph1CfmoKfT'
BASE_PATH ='https://open.bigmodel.cn/api/paas/v4/'
model = ChatOpenAI(model_name='glm-4',temperature=.7,openai_api_key=ZHIPUAI_API_KEY,base_url=BASE_PATH)


# 聊天历史保存
# from langchain.memory import ChatMessageHistory
# history=ChatMessageHistory()
# history.add_user_message('hi')
# history.add_ai_message("what's up")

conversation = ConversationChain(
    llm=model,
    verbose=True,
    memory=ConversationBufferMemory()
)

conversation.predict(input='您好我猫丢了怎么办')
conversation.predict(input='我找回了我的猫但是我的猫食欲低下怎么办')
 
 
# #保存会话到硬盘

dicts = messages_to_dict(conversation.memory.chat_memory.messages)
# 打开一个文件用于写入
with open('memory', 'wb') as f:
    # 将字典对象序列化并保存到文件
    pickle.dump(dicts, f)

# #加载会话
with open('memory', 'rb') as f:
    # 读取并反序列化数据
    data_loaded = pickle.load(f)
 
history_msg = messages_from_dict(data_loaded)
print(history_msg)
     
recv_msg = ChatMessageHistory(messages=history_msg)
recv_memory = ConversationBufferMemory(chat_memory=recv_msg)

recv_conversation = ConversationChain(
    llm=model,
    verbose=True,
    memory=recv_memory
)

recv_conversation.predict(input="我回来了")